import { Injectable } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  // 声明主题对象
  public subject: Subject<any> = new Subject<any>();


  /**
   * 获得信息
   *
   * @returns {Observable<any>} 返回消息的监听
   * @memberof MessageService
   */
  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }


  /**
   * 信息传输，类似广播
   *
   * @param {*} msg 信息内容
   * @memberof MessageService
   */
  sendMessage(msg: any) {
    if (msg) {
      this.subject.next(msg);
    }
  }

  /**
   * 发送消息给指定的订阅者
   * @ param msg 
   * @ param uuid
   */
  sendMessageById(msg: any, uuid) {
    if (msg) {
      const observersLen = this.subject.observers.length;
      if (observersLen > 0) {
        this.subject.observers[observersLen - 1].next(msg);
      } else {
        return;
      }
    }
  }


  /**
   * 清理消息
   *
   * @memberof MessageService
   */
  clearMessage() {
    this.subject.next();
  }

  constructor() { }
}
